<script>
import {useRouter} from "vue-router";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, reactive,ref,shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import TextEditor from '../../components/TextEditor.vue'
import { SERVER_HOST } from "../../config";
import {ElMessage, ElMessageBox} from "element-plus";
import {add_news_info, edit_news_info, get_news_detail} from "../../api";




export default {
  name: "CrecteOrEdit",
  components: { Editor, Toolbar ,TextEditor},
  props: {
    newsId: String
  },
  setup(props){
    const router = useRouter();

    onMounted(()=>{
      if(props.newsId){
        getDtail()

      }
    })

    const formData = reactive({
      id:'',
      title:'',
      headline:[],
      content:'',
      news_type_id:'',
      author:'',
      is_banner: '',
      status: '',
      create_time:'',
      is_delete: '',
      delete_time: '',
      remarks: ''

    })


    const getDtail=()=>{
      get_news_detail(props.newsId).then((res) => {
        console.log(res)
        var code = res.code;
        if (code===200){
          let newsData = res.data[0]
          formData.id = newsData.id
          formData.title = newsData.title
          formData.news_type_id = newsData.news_type_id
          formData.author = newsData.author
          formData.is_banner = newsData.is_banner
          formData.headline = newsData.headline
          formData.content = newsData.content
          for (let img of newsData.headline) {
            fileList.value.push({url:img})
          }
        console.log(fileList.value)
          console.log()
        }else if(code===401){
          ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
            confirmButtonText: "确定",
            callback: action => {
              sessionStorage.clear()
              localStorage.removeItem("user_name");
              localStorage.removeItem("token");
              console.log('用户信息已清除')
              router.push('/login')
            }
          });
        }

      })
    }

    let Back = () => {

      router.back()
      // window.location.reload(); // 刷新当前页面
      // showToast('返回成功')

    }

// 步骤条
    const currentStepActive = ref(0)
    const  currentStepText = ref('下一步')
    const  stepBtnType = ref('primary')

// 步骤条按钮
    const next = () => {
      if (currentStepActive.value<3){
        currentStepActive.value+=1
      }


      if (currentStepActive.value === 1){
        currentStepText.value = '下一步'
        stepBtnType.value = 'primary'
        if (formData.title===""){
          ElMessage.warning("新闻标题不能为空！");
          currentStepActive.value = 0
        }else if (formData.news_type_id===""){
          ElMessage.warning("新闻类别不能为空！");
          currentStepActive.value = 0
        }else if (formData.author===""){
          ElMessage.warning("新闻作者不能为空！");
          currentStepActive.value = 0
        }else if (formData.is_banner===""){
          ElMessage.warning("请选择是否置顶banner！");
          currentStepActive.value = 0
        }
      }
      if  (currentStepActive.value === 2){
        currentStepText.value = ' 发布 '
        stepBtnType.value = 'success'
        if (formData.headline.length===0){
          ElMessage.warning("封面图不能为空！");
          currentStepActive.value = 1
          currentStepText.value = ' 下一步 '
          stepBtnType.value = 'primary'
        }
      }

      if  (currentStepActive.value === 3){
        if (formData.content===""){
          ElMessage.warning("新闻内容不能为空！");
          currentStepActive.value = 2
        }else{
          console.log('可以发布了')
          if(props.newsId){
            editSubmit()
          }else{
            addSubmit()
          }

        }
      }
    }
// 步骤条按钮
    const previousStep = () => {
      currentStepActive.value--
      if (currentStepActive.value<0){
        currentStepActive.value =0
      }
      if (currentStepActive.value === 0){
        currentStepText.value = '下一步'
        stepBtnType.value = 'primary'
      }else if (currentStepActive.value === 1){
        currentStepText.value = '下一步'
        stepBtnType.value = 'primary'
      }
    }


    let form = reactive({
      id:0,
      title:"",
      headline:"",
      author:"",
      news_type:"",
      content:"",
      status:"",
      is_banner:""
    });


    const addNewsInfo = reactive({
      title:"",
      headline:[],
      news_type_id:"",
      author:"",
      content:"",
      is_banner:""

    })

    //  发布新闻
    const addSubmit = ()=>{
          add_news_info(formData).then((res) => {
            var code=res.code
            if (code===200){
              ElMessage.success(''+res.msg);
              formData.title=""
              formData.headline=[]
              formData.news_type_id=""
              formData.author=""
              formData.content=""
              formData.is_banner=""
              router.push('/newstable')
            }else if(code===401){
              ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
                confirmButtonText: "确定",
                callback: action => {
                  router.push('/login')
                }
              });
            }else {
              ElMessage.error(''+res.msg)
            }
          });
        }


    // 编辑新闻
    const editSubmit = ()=>{
      edit_news_info(formData).then((res) => {
        var code=res.code
        if (code===200){
          ElMessage.success(''+res.msg);
          formData.id=""
          formData.title=""
          formData.headline=[]
          formData.news_type_id=""
          formData.author=""
          formData.content=""
          formData.is_banner=""
          router.push('/newstable')
        }else if(code===401){
          ElMessageBox.alert("未授权或登录过期，请重新登录", "提示", {
            confirmButtonText: "确定",
            callback: action => {
              router.push('/login')
            }
          });
        }else {
          ElMessage.error(''+res.msg)
        }
      });

    }

    const handleAdd = () => {
      form.img=''
      form.commodity_name=''
      form.color=''
      form.sku=''
      form.status=''
      form.commodity_code=''
      form.description=''
      form.price=''
      addVisible.value = true;
    };



    let idx = -1;
    let fileList= ref([]);
    let imgList= ref([]);
    let imgobj=ref({
      url:""
    })
    const handleAvatarSuccess=(resource) =>{
      imgobj.url=resource.data.file_url;
      fileList.value.push(imgobj)
      formData.headline.push(imgobj.url)
      console.log(formData.headline)
      console.log(fileList.value)
    };

    // 删除图片时候同步到表单删除
    const handleRemove=(file, fileList)=> {
      const index = fileList.findIndex((item) => {
        return item.uid === file.uid
      })
      formData.headline.splice(index, 1)
      fileList.splice(index, 1)
    }

    const editstart=(file)=>{
      handleRemove(file)
    }
  const upValueEvent = () =>{

  }


  //  富文本编辑器相关
  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef()

  // 内容 HTML
  const valueHtml = ref('<p>hello</p>')
    const toolbarConfig = {

    }
    const editorConfig = {
      placeholder: '请输入内容...' ,
      MENU_CONF:{
        uploadImage:{
          server:SERVER_HOST+'/fileInfo',
          fieldName: 'file',
          customInsert(res, insertFn) {
            console.log(res.data.file_url)
            insertFn(res.data.file_url)
          }
        }
      },
      fontSize: {
        fontSizeList: [
          // 元素支持两种形式
          //   1. 字符串；
          //   2. { name: 'xxx', value: 'xxx' }

          '12px',
          '16px',
          { name: '24px', value: '24px' },
          '40px',
        ]
      }
    }

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    return {
      Back,
      handleAdd,
      handleAvatarSuccess,
      previousStep,
      next,
      editstart,
      addSubmit,
      handleCreated,
      handleRemove,
      editorRef,
      valueHtml,
      fileList,
      toolbarConfig,
      editorConfig,
      addNewsInfo,
      mode: 'simple', // 或 'simple'
      props,
      currentStepActive,
      currentStepText,
      stepBtnType,
      formData,
      SERVER_HOST
    };
  },
};
</script>

<template>

        <el-page-header @back="Back()">
          <template #content>
            <div class="flex items-center">
              {{props.newsId?'编辑'+props.newsId : '新闻发布'}}
            </div>
          </template>
        </el-page-header>
        <div class="card-box">
          <el-card >
            <el-steps  class="mb-4" simple style="max-width: 100%" :active="currentStepActive" finish-status="success">
              <el-step title="基本信息" />
              <el-step title="新闻头图" />
              <el-step title="新闻内容" />
            </el-steps>
            <el-form v-show="currentStepActive===0" label-width="70px">
              <br>
              <br>
              <el-form-item v-show="newsId" label="新闻Id">
                <el-input  v-model="formData.id" disabled></el-input>
              </el-form-item>
              <el-form-item label="新闻标题">
                <el-input v-model="formData.title"></el-input>
              </el-form-item>

              <el-form-item label="新闻分类">
                <el-select v-model="formData.news_type_id" placeholder="新闻类别" clearable class="handle-select mr10">
                  <el-option key="1" label="国内" value="1"></el-option>
                  <el-option key="2" label="国际" value="2"></el-option>
                  <el-option key="3" label="娱乐" value="3"></el-option>
                  <el-option key="4" label="军事" value="4"></el-option>
                  <el-option key="5" label="体育" value="5"></el-option>
                  <el-option key="6" label="科技" value="6"></el-option>
                  <el-option key="7" label="财经" value="7"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="新闻作者" placeholder="请输入作者姓名/昵称">
                <el-input  style="width: 220px" v-model="formData.author"></el-input>
              </el-form-item>
              <el-form-item  label="是否置顶">
                <el-select  v-model="formData.is_banner" placeholder="请选择是否置顶" class="handle-select mr10">
                  <el-option key="0" label="不置顶" value="0"></el-option>
                  <el-option key="1" label="置顶" value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-form>

            <el-form v-show="currentStepActive===1" label-width="200px">
              <br>
              <br>
              <el-form-item label="请上传新闻头图">
                <el-upload
                    :action="SERVER_HOST+'/fileInfo'"
                    list-type="picture-card"
                    :file-list="fileList"
                    :on-success="handleAvatarSuccess"
                    :on-remove="handleRemove">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-form>

            <el-form v-show="currentStepActive===2" label-width="70px">
              <br>
              <br>
              <el-form-item label="新闻内容">
                <div style="border: 1px solid #ccc">
                  <Toolbar
                      style="border-bottom: 1px solid #ccc"
                      :editor="editorRef"
                      :defaultConfig="toolbarConfig"

                  />
                  <Editor
                      style="height: 500px; overflow-y: hidden;"
                      v-model="formData.content"
                      :defaultConfig="editorConfig"

                      @onCreated="handleCreated"
                  />
                </div>
<!--                <TextEditor v-model="addNewsInfo.content" @upValue-Event="upValueEvent"/>-->
              </el-form-item>
            </el-form>
            <el-button type="primary" style="margin-top: 12px" @click="previousStep">上一步</el-button>
            <el-button :type="stepBtnType" style="margin-top: 12px" @click="next">{{ currentStepText }}</el-button>
          </el-card>
        </div>



</template>



<style scoped>
.card-box{
  margin-top: 10px;
}


</style>
